package com.cc.inter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 再次封装发送请求，以及对返回结果进行处理需要依赖:fastjson、
 * @author cc
 * @create 2020-04-26-9:02
 */
public class InterKw {
    //用来存储需要传递的参数
    private Map<String,String> transParams;
    //封装httpclient发送的请求
    private HttpClientKW http;
    //每次请求的结果
    public String tmpResponse;


    public InterKw(){

    }

    /**
     * 构造方法个http赋值
     * @param http
     */
    public InterKw(HttpClientKW http){
        this.http = http;
        this.transParams = new HashMap<String, String>();

    }

    /**
     * 实现保存参数的传递，保存参数的形式标记的"{parm}"==>transParms.get(parms)
     * @param params
     * @return
     */
    private String transferParms(String params){
        String res = params;
        for(String key:transParams.keySet()){
            res = res.replaceAll("\\{" +key+"\\}",transParams.get(key).toString());
        }
        return res;

    }

    private String re(String rex){
        Pattern p = Pattern.compile(rex);
        Matcher m = p.matcher(tmpResponse);
        if(m.find()){
            return m.group(1);
        }else{
            return null;
        }
    }

    /**
     * 使用cookie
     */
    public void useCookie(){
        http.useCookie();
    }

    /**
     * 不使用cookie
     */
    public void unuseCookie(){
        http.unuseCookie();
    }

    /**
     * 清空cookie
     */
    public void clearCookie(){
        http.clearCookie();
    }

    /**
     * 添加到头部信息中，需要形参json类型的字符串
     * @param jsonString
     */
    public void addHeader(String jsonString){
        //参数进行空和空字符判断
        if(jsonString==null||jsonString.equals("")){
            return;
        }
        //参数传递
        try {
            jsonString = transferParms(jsonString);
            Map<String,String> jsonMap = new HashMap<String, String>();
            //将json字符串转换成字典
            if(jsonString.startsWith("{")&&jsonString.endsWith("}")&&jsonString.length()>4) {
                JSONObject jsonObject = JSONObject.parseObject(jsonString);
                for(String key : jsonObject.keySet()){
                    jsonMap.put(key,jsonObject.getString(key));
                }
            }
            http.addHeader(jsonMap);
        } catch (Exception e) {
            e.fillInStackTrace();
        }


    }

    /**
     * 使用额外的头部信息
     */
    public void useHeader(){
        http.useHeader();
    }

    /**
     * 不使用额外的头部信息
     */
    public void unuseHeader(){
        http.unuseHeader();
    }

    /**
     * 通过jsonpath的路径读取需要保存的结果，返回结果必须时json字符串
     * @param key
     * @param jsonPath
     */
    public void saveJson(String key,String jsonPath){
        String value = "";
        //通过jsonpath路径读取结果
        try {
            value = JSONPath.read(tmpResponse,jsonPath).toString();
            transParams.put(key,value);
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    /**
     * 通过正则对返回结果进行读取保存
     * @param key 需要存储的键值
     * @param rex 正则表达式 左边界(.*?)右边界，去匹配到结果括号内容
     */
    public void saveRex(String key,String rex){

       String res = re(rex);
       if(res!=null){
           transParams.put(key,res);
       }else{
           System.out.println("没有配=匹配到");
       }

    }

    /**
     * 接口地址url设置
     * @param url
     */
    public void setUrl(String url){
        http.setUrl(url);
    }

    public void get(String path,String params){
        params = transferParms(params);
        tmpResponse = http.doGet(path,params);
        System.out.println(tmpResponse);

    }

    public void postData(String path,String params){
        params = transferParms(params);
        tmpResponse = http.postData(path,params);

    }

    public void postJson(String path,String params){
        params = transferParms(params);
        tmpResponse = http.postJson(path,params);

    }

    public void put(String path,String params){
        params = transferParms(params);
        tmpResponse = http.put(path,params);
    }

    public void delete(String path,String params){
        params = transferParms(params);
        tmpResponse = http.delete(path,params);
    }




}
class InterTest{
    public static void main(String[] args) {
        HttpClientKW httpClientKW = new HttpClientKW();
        InterKw inter = new InterKw(httpClientKW);
        inter.setUrl("http://testingedu.com.cn:8081/inter/HTTP");
        inter.postData("auth","");
        System.out.println(inter.tmpResponse);
        inter.saveRex("token","\"token\":\"(.*?)\"}");
        //inter.saveJson("token","$.token");
        inter.addHeader("{\"token\":\"{token}\"}");
        inter.useHeader();
        inter.postData("login","username=chencheng&password=123456");
        System.out.println(inter.tmpResponse);
        //inter.saveJson("userid","$.userid");
        inter.saveRex("userid","\"userid\":\"(.*?)\"}");
        inter.postData("getUserInfo","id={userid}");
        System.out.println(inter.tmpResponse);
        inter.postData("logout","");
        System.out.println(inter.tmpResponse);


    }
}
